package com.gln.bloger.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorActionForm;

import com.gln.bloger.constant.Constant;
import com.gln.bloger.pojos.Comment;

/**
 * Created on 20080115
 * @author renxj
 * modify entries/articles 
 */
public class CommentAction extends GuestBaseAction {
	/**
	 * save comment 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward post(ActionMapping mapping, ActionForm form,
		   HttpServletRequest request, HttpServletResponse response) 
	       throws Exception{
		DynaValidatorActionForm commentForm = (DynaValidatorActionForm) form;
		String entryId = commentForm.getString("entryId");
		String authorName = commentForm.getString("authorName");
		String authorMail = commentForm.getString("authorMail");
		String authorSite = commentForm.getString("authorSite");
		String content = commentForm.getString("content");
		String code = commentForm.getString("code");
		Comment comment = new Comment();
		comment.setAuthorMail(authorMail);
		comment.setAuthorName(authorName);
		comment.setAuthorSite(authorSite);
		comment.setContent(content);
		comment.setPostIP(request.getRemoteHost());
		comment.setStatus(Comment.Status.APPROVED);
		comment.setPostTime(new Date());
		
		if(getAuthUser(request) == null){
			comment.setStatus(Comment.Status.WAIT_FOR_APPROVE);
			
			ActionMessages errors = commentForm.validate(mapping, request);
			String sessionIdentifyingCode = (String)request.getSession().
            getAttribute(Constant.IDENTIFYING_CODE_SESSION_NAME);
			
			if(!code.equalsIgnoreCase(sessionIdentifyingCode)){
				errors.add("errors", new ActionMessage("errors.mismatch.identifyCode"));
			}
			
			if(!errors.isEmpty()){
				request.setAttribute("comment", comment);
				saveErrors(request, errors);
				return new ActionForward("/entry.do?method=show&id="+entryId);
			}
		}
		
		this.getCommentService().saveOrUpdateComment(comment, entryId);
		/**
		 * clear recent comment cache
		 */
		this.getCommentService().clearCachedRecentComments();
		return new ActionForward("/entry.do?method=show&id="+entryId);
	}
}
